<template>
<div>
   <el-dialog
      title="选择配件"
      :visible.sync="isShow"
      class="appWorkDialog"
      @opened="resetData"
      @close="closeDialog"
      :close-on-click-modal="false"
      width="80%"
    >
      <!-- 查询表单 -->
    <el-form
      ref="serachForm"
      :model="serachForm"
      labelPosition="right"
      inline=""
      label-suffix=":"
      label-width="110px"
    >
        <el-form-item label="品牌车系车型">
          <el-cascader
            v-model="brandss"
            :props="props"
            @change="getChange"
            :show-all-levels="false"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="配件名称">
          <el-input
            v-model="serachForm.name"
            size="small"
            placeholder=""
          ></el-input>
        </el-form-item>
       <el-form-item>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="initTableData()"
          >
            查询
          </el-button>
          <el-button
            icon="el-icon-refresh-left"
            size="small"
            @click="dataReset"
            >重置
          </el-button>
        </el-form-item>
    </el-form>
    <div style="height:300px">
      <el-table
        ref="tblMain"
        style="margin-top: 20px"
        :data="listData"
        height="100%"
        :row-key="getRowKeys"
        @selection-change="handleSelectionChange"
        @sort-change="getSortList"
        v-loading.body="loading"
        border
        stripe
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
          prop="id"
          :reserve-selection="true"
        ></el-table-column>
          <!-- :selectable='selectEnable' -->

        <el-table-column
          type="index"
          width="50"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="imgName"
          label="图片"
          align="center"
        >
        <template slot-scope="scope">
          <img :src="scope.row.imgName" style="width:30px;height:30px" />
        </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="配件名称"
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="matAttrCodeb"
          label="配件属性"
          align="center"
        >
        <template slot-scope="scope">
           {{ formatterFiled(scope.row.matAttrCodeb,'id','name',classifyList) }}
        </template>
        </el-table-column>
        <el-table-column
          prop="mfrs"
          label="制造商"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="model"
          label="型号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="color"
          label="颜色"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="expiryNum"
          label="保质期天数"
          align="center"
        ></el-table-column>
      </el-table>
    </div>
    <el-pagination
      style="margin-top: 10px"
      :current-page.sync="pageInfo.page"
      :page-size="pageInfo.size"
      :total="pageInfo.total"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirmMar()">确 定</el-button>
      </div>
    </el-dialog>

</div>

</template>

<script>
import {
  getMaterialList,
  getCarLetterList,
  getCarBrandList,
  getCarList,
  getCarClassifyList
} from '@/api/carLine'
export default {
  name: "gbjTable",
  props: {
    isShow:{
      type: Boolean,
      default: false
    },
    hasCheck:{
      type: Array,
      default: []
    },
  },
  data() {
    return {
      // 获取表格row的key值
      getRowKeys(row) {
        return row.id;
      },
      props: {
        lazy: true,
        checkStrictly: true,
        lazyLoad(node, resolve) {
          const { level, data } = node
          setTimeout(() => {
            if (level == 0) {
              let data = {
                page: 1,
                size: 1000
              }
              getCarLetterList(data).then((res) => {
                const { code = undefined, data = {} } = res.data
                if (!code) {
                  const nodes = data.content.map((item) => ({
                    value: item.id,
                    label: item.name,
                    leaf: false
                  }))
                  resolve(nodes)
                } else {
                  this.$message.error(data)
                }
              })
            } else if (level == 1) {
              let param = {
                page: 1,
                size: 1000,
                letterId: data.value
              }
              getCarBrandList(param)
                .then((res) => {
                  const { code = undefined, data = {} } = res.data
                  if (!code) {
                    // this.brands = data.content;
                    const nodes = data.content.map((item) => ({
                      value: item.id,
                      label: item.name + ' - ' + item.makeName,
                      leaf: false
                    }))
                    resolve(nodes)
                  }
                })
                .catch(() => {
                  this.$message.error('服务器繁忙')
                })
            } else if (level == 2) {
              let param = {
                page: 1,
                size: 1000,
                brandId: data.value
              }
              getCarList(param)
                .then((res) => {
                  const { code = undefined, data = {} } = res.data
                  if (!code) {
                    // this.brands = data.content;
                    const nodes = data.content.map((item) => ({
                      value: item.id,
                      label: item.vehicleModel,
                      leaf: true
                    }))
                    resolve(nodes)
                  }
                })
                .catch(() => {
                  this.$message.error('服务器繁忙')
                })
            } else {
              resolve([])
            }
          }, 1000)
        }
      },
      rowData: {},
      title: '',
      levelList: [],
      classifyList:[],
      loading: false,
      listData: [],
      selection: [],
      serachForm: {
        carId: '',
        name: '',
        mfrs: '',
        order:""
      },
      pageInfo: {
        page: 1,
        size: 10,
        total: 0
      },
      brands: [],
      brandss: ''
    };
  },
  computed: {},
  created() {
  },
  mounted() {
    //  this.getBrandsList().then(() => {
    //   this.getTopParentList()
    //   // this.serachForm.brandName = this.levelList[0].name !='所有品牌'? this.levelList[0].name:"";
    //   this.initTableData()
    // })
  },
  methods: {
    /**
    *  排序查询
    */
    getSortList(column) {
      let arr = [];
      arr.push(column.prop);
      arr.push( column.order.substring(
           0,
           column.order.indexOf("ending")
       ))
      this.serachForm.order = arr.join(',');
      this.initTableData()
    },
     /**
     * 多选
     */
    handleSelectionChange(val) {
      this.selection = val
    },
     /**
     * 获取码值
     */
     formatterFiled(cellValue,key,val,list) {
      let item = list.find((item) => item[key] === cellValue)
      return item ? item[val] : ''
    },
     /**
     * 获取配件分类的树形数据
     */
     getTopParentList() {
      let param = {
        page: 1,
        size: 1000
      }
      getCarClassifyList(param)
        .then((res) => {
          const { code = undefined, data = {} } = res.data
          if (!code) {
            this.classifyList = data.content
          } else {
            this.$message.error('获取配件分类失败')
          }
        })
        .catch(() => {
          this.$message.error('服务器繁忙')
        })
    },
    /**
     * 获取品牌级联数据
     */
    getChange(val) {
      this.serachForm.carId = val[val.length - 1]
    },
    /**
     * 获取品牌列表信息
     */
    getBrandsList() {
      return new Promise((resolve) => {
        let data = {
          page: 1,
          size: 1000
        }
        getCarLetterList(data).then((res) => {
          const { code = undefined, data = {} } = res.data
          if (!code) {
            this.brands = data.content
            resolve(this.brands)
          } else {
            this.$message.error(data)
          }
        })
      })
    },
    /**
     * 获取车系信息
     */
    getCarBrandList(letterId) {
      let param = {
        page: 1,
        size: 1000,
        letterId
      }
      return new Promise((resolve) => {
        getCarBrandList(param)
          .then((res) => {
            const { code = undefined, data = {} } = res.data
            if (!code) {
              // this.brands = data.content;
              resolve(data.content)
            }
          })
          .catch(() => {
            this.$message.error('服务器繁忙')
          })
      })
    },
    /**
     * 获取车型信息
     */
    getCarList(letterId) {
      let param = {
        page: 1,
        size: 1000,
        letterId
      }
      return new Promise((resolve) => {
        getCarList(param)
          .then((res) => {
            const { code = undefined, data = {} } = res.data
            if (!code) {
              // this.brands = data.content;
              resolve(data.content)
            }
          })
          .catch(() => {
            this.$message.error('服务器繁忙')
          })
      })
    },
     /**
     * 获取配件数据列表
     */
    initTableData() {
      this.selection = []
      let param = {
        page: this.pageInfo.page,
        size: this.pageInfo.size,
        ...this.serachForm
      }
      this.loading = true
      getMaterialList(param)
        .then((res) => {
          this.loading = false
          const { code = undefined, data = {} } = res.data
          if (!code) {
            this.listData = data.content;
            let arr = [];
            console.log(this.hasCheck);
            data.content.forEach(item=>{
              this.hasCheck.forEach(el=>{
                if(el.productId == item.id){
                  arr.push(item)
                }
              })
            })
            if (arr.length) {
              arr.forEach(row => {
                this.$refs.tblMain.toggleRowSelection(row);
              });
            }
            this.pageInfo.total = data.totalElements;
          }else{
            this.$message.error(data)
          }
        })
        .catch(() => {
          this.$message.error('服务器繁忙')
          this.loading = false
        })
    },
    /**
     * 分页
     */
    handleSizeChange(val) {
      this.pageInfo.size = val
      this.initTableData()
    },
    /**
     * 分页
     */
    handleCurrentChange(val) {
      this.pageInfo.page = val
      this.initTableData()
    },
    /**
     * 重置
     */
    dataReset() {
      this.pageInfo.page = 1
      this.pageInfo.size = 10
      this.brandss = ''
      this.serachForm.name = ''
      this.serachForm.carId = ''
      this.serachForm.order = ''
      this.initTableData()
    },
    //打开弹框
    resetData(){
      this.$nextTick(() => {
        this.$refs.tblMain.clearSelection();
      });
      console.log(this.hasCheck);
      this.getBrandsList().then(() => {
        this.getTopParentList()
        this.initTableData()
      })
    },
    //把已选择的项禁用
    selectEnable(row, rowIndex) {
      let arr = this.hasCheck.map(item=>{
        return item.productId
      })
      if(arr.indexOf(row.id) == -1){
        return true;
      }else{
        return false;
      }
     },
    confirmMar() {
      let arr = [],ids = []
      this.selection.forEach(item=>{
        this.hasCheck.forEach(el=>{
          if(el.productId == item.id){
            ids.push(item.id)
          }
        })
      })
      this.selection.forEach(item=>{
        if(ids.indexOf(item.id) == -1){
          let op = {
            id:null,
            productId:item.id,
            productName:item.name
          }
          arr.push(op)
        }else{
          this.hasCheck.forEach(el=>{
            if(el.productId == item.id){
              arr.push(el)
            }
          })
        }
      })
      let checkRows = arr
      this.$emit('confirmMar',checkRows )
      this.closeDialog()
    },
    closeDialog(){
      this.$emit("update:isShow", false);
    },
  }
};
</script>

<style lang="scss" scoped>
.dialog {
  .textarea {
    ::v-deep .el-form-item__label {
      width: 120px !important;
    }
  }
}
</style>
